package com.avcdata.national.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.activity.Login_Activity;
import com.avcdata.aoscustommade.activity.Main_Activity;
import com.avcdata.aoscustommade.adapter.MyWheelAdapter;
import com.avcdata.aoscustommade.utils.AvcConstants;
import com.avcdata.aoscustommade.utils.MyXValueFormatter;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.avcchart.linechart.chart.AvcLineCharts;
import com.avcdata.national.activity.ScaleBasisRatioActivity;
import com.avcdata.national.adapter.allLableAdapter;
import com.avcdata.national.module.AllLableBean;
import com.avcdata.national.module.ScaleBasicRationInfo;
import com.avcdata.national.module.ScaleRationTrendInfo;
import com.avcdata.national.network.BaseLog;
import com.avcdata.national.network.JsonRunnable;
import com.avcdata.national.network.ThreadPoolUtils;
import com.avcdata.national.utils.HorizontalListView;
import com.avcdata.national.utils.MyBaseFragment;
import com.avcdata.national.utils.MyUtils;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wx.wheelview.widget.WheelView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lecho.lib.hellocharts.listener.ColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.view.ColumnChartView;

import static com.avcdata.aoscustommade.R.id.account;
import static com.avcdata.aoscustommade.R.id.dialog_cancel;
import static com.avcdata.aoscustommade.utils.AvcConstants.URL_ScaleBasisRatio;

/**
 * 行业规模页面
 * Created by Lucasey on 2017/8/22.
 */

public class ScaleFragment extends MyBaseFragment implements OnChartGestureListener, OnChartValueSelectedListener {

    @ViewInject(R.id.sale_type)
    private LinearLayout sale_type;
    @ViewInject(R.id.sale_text)
    private TextView sale_text;
    @ViewInject(R.id.line_type)
    private LinearLayout line_type;
    @ViewInject(R.id.line_text)
    private TextView line_text;
    @ViewInject(R.id.week_type)
    private LinearLayout week_type;
    @ViewInject(R.id.week_text)
    private TextView week_text;

    @ViewInject(R.id.barchart)
    private ColumnChartView mChart;
    @ViewInject(R.id.linechart_view)
    private AvcLineCharts linechart_view;

    private LinearLayout loading;

    @ViewInject(R.id.all_lable)
    private HorizontalListView lableListView;

    private String measureString = "online";
    private String weekString = "current";
    private String saleString = "amount";
    private String measureStringTemp = "";
    private String weekStringTemp = "";
    private String saleStringTemp = "";

    private Dialog dialog;
    private ArrayList<String> dataMeasure;
    private ArrayList<String> weeks;
    private ArrayList<String> sales;

    private ScaleBasisRatioActivity scaleBasisRatioActivity;

    private List<String> brands = new ArrayList<>();

    private ArrayList<ArrayList<HashMap<String, String>>> data;
    private ArrayList<String> key;

    private List<TextView> marketRatio;

    @ViewInject(R.id.brands_tip)
    private TextView brands_tip;
    @ViewInject(R.id.brands1)
    private TextView brands1;
    @ViewInject(R.id.brands2)
    private TextView brands2;
    @ViewInject(R.id.brands3)
    private TextView brands3;
    @ViewInject(R.id.brands4)
    private TextView brands4;
    @ViewInject(R.id.brands5)
    private TextView brands5;
    @ViewInject(R.id.brands6)
    private TextView brands6;
    @ViewInject(R.id.brands7)
    private TextView brands7;

    private List<String> userbrands = new ArrayList<>();

    List<AllLableBean> listLable = new ArrayList<> ();
    allLableAdapter adapter;
    ArrayList<Integer> colors = new ArrayList<>();
    ArrayList<Integer> colors2 = new ArrayList<>();

    @Override
    protected View onLayoutView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_national_sacle, container, false);
    }

    @Override
    protected void initView(View container, Bundle savedInstanceState) {
        ViewUtils.inject(this,container);
        week_type.setOnClickListener(this);
        line_type.setOnClickListener(this);
        sale_type.setOnClickListener(this);
        scaleBasisRatioActivity = (ScaleBasisRatioActivity) getActivity();
        loading = scaleBasisRatioActivity.getLoading();
        userbrands = new ArrayList<>(new SharedPreferencesUtils(scaleBasisRatioActivity).getCompetingBrands(scaleBasisRatioActivity.getCategory()));
        for(String str: userbrands){
            BaseLog.e(scaleBasisRatioActivity.getCategory()+"：","<===>"+str);
        }
        initOnCreate();
    }



    private void initOnCreate() {
        loading.setVisibility(View.GONE);

        marketRatio = new ArrayList<>();
        marketRatio.add(brands1);
        marketRatio.add(brands2);
        marketRatio.add(brands3);
        marketRatio.add(brands4);
        marketRatio.add(brands5);
        marketRatio.add(brands6);
        marketRatio.add(brands7);

        //设置同比环比
        brands_tip.setText("同比");

        dataMeasure = new ArrayList<>();
        dataMeasure.add("线上");
        dataMeasure.add("线下");
        weeks = new ArrayList<>();
        weeks.add("当前周");
        weeks.add("近四周");
        weeks.add("近八周");
        weeks.add("本年累计");
        sales = new ArrayList<>();
        sales.add("销量");
        sales.add("销额");
        //设置线上线下方式
        if(new SharedPreferencesUtils(getActivity()).getLineType() == 1  ){
            line_text.setText("线上");
            measureString = "online";
        }else{
            line_text.setText("线下");
            measureString = "offline";
        }
        //设置周度
        switch (new SharedPreferencesUtils(getActivity()).getWeekType()){
            case "近四周":
                week_text.setText("近四周");
                weekString = "fourWeek";
                break;
            case "近八周":
                week_text.setText("近八周");
                weekString = "eightWeek";
                break;
            case "本年累计":
                week_text.setText("本年累计");
                weekString = "year";
                break;
            case "当前周":
                week_text.setText("当前周");
                weekString = "current";
                break;
            default:
                week_text.setText("当前周");
                weekString = "current";
                break;
        }
        //设置销量销额方式
        if(new SharedPreferencesUtils(getActivity()).getSaleType() == 1  ){
            sale_text.setText("销量");
            saleString = "volume";
        }else{
            sale_text.setText("销额");
            saleString = "amount";
        }

        //初始化点击标签
        colors = TextUitl.getColor();
        colors2 = TextUitl.getColor();
        for(int i=0;i<colors2.size();i++){
            if(i == 0 || i==1){
            }else{
                colors2.set(i,Color.parseColor ("#00000000"));
            }
        }
        getBrandScaleBasisRatio();
    }


    @Override
    protected void onclickEvent(View view) {
        switch (view.getId()){
            case R.id.sale_type:
                showDialogSelect(1);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.line_type:
                showDialogSelect(3);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.week_type:
                showDialogSelect(2);
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
                break;
            default:
                break;
        }
    }

    /***
     * 获取选择的索引
     * @param dataTemp
     * @param stringTemp
     * @return
     */
    private int getSelectPosition(ArrayList<String> dataTemp, String stringTemp) {
        int temp = 0;
        for (int i = 0; i < dataTemp.size(); i++) {
            if (dataTemp.get(i).equals(stringTemp)) {
                temp = i;
            }
        }
        return temp;
    }

    /***
     *单选dialog
     * @param dialogNum 3-线上线下/2-最新周···
     */
    private void showDialogSelect( final int dialogNum) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_single, null);
        dialog = new Dialog(getActivity(), R.style.DialogBlack);
        Window window = dialog.getWindow();
        window.setContentView(view);
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);

        final TextView dialog_title1 = (TextView) view.findViewById(R.id.dialog_title1);
        TextView dialog_title2 = (TextView) view.findViewById(R.id.dialog_title2);
        final WheelView wheelview_single1 = (WheelView) view.findViewById(R.id.wheelview_single1);
        final WheelView wheelview_single2 = (WheelView) view.findViewById(R.id.wheelview_single2);
        dialog_title2.setVisibility(View.GONE);
        wheelview_single2.setVisibility(View.GONE);
        wheelview_single1.setSkin(WheelView.Skin.None);
        WheelView.WheelViewStyle style = new WheelView.WheelViewStyle();
        style.selectedTextColor = Color.RED;
        style.selectedTextSize = 20;
        style.textColor = Color.BLACK;
        wheelview_single1.setStyle(style);
        wheelview_single1.setLoop(false);
        wheelview_single1.setWheelClickable(false);
        switch (dialogNum) {
            case 1:
                dialog_title1.setText("选择销量销额");
                wheelview_single1.setWheelData(sales);
                wheelview_single1.setSelection(getSelectPosition(sales, saleStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(getActivity()));
                break;
            case 2:
                dialog_title1.setText("选择周度时长");
                wheelview_single1.setWheelData(weeks);
                wheelview_single1.setSelection(getSelectPosition(weeks, weekStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(getActivity()));
                break;
            case 3:
                dialog_title1.setText("选择销售状况");
                wheelview_single1.setWheelData(dataMeasure);
                wheelview_single1.setSelection(getSelectPosition(dataMeasure, measureStringTemp));
                wheelview_single1.setWheelSize(3);
                wheelview_single1.setWheelAdapter(new MyWheelAdapter(getActivity()));
                break;
            default:
                break;
        }

        view.findViewById(dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        view.findViewById(R.id.dialog_ensure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (dialogNum) {
                    case 1:
                        saleStringTemp = sales.get(wheelview_single1.getCurrentPosition());
                        sale_text.setText(saleStringTemp);
                        if (sales.get(wheelview_single1.getCurrentPosition()).equals("销量")) {
                            saleString = "volume";
                            sale_text.setText("销量");
                            new SharedPreferencesUtils(getActivity()).setSaleType(1);
                        } else {
                            saleString = "amount";
                            sale_text.setText("销额");
                            new SharedPreferencesUtils(getActivity()).setSaleType(2);
                        }
                        break;
                    case 2:
                        weekStringTemp = weeks.get(wheelview_single1.getCurrentPosition());
                        week_text.setText(weekString);
                        switch (weekStringTemp){
                            case "近四周":
                                week_text.setText("近四周");
                                weekString = "fourWeek";
                                new SharedPreferencesUtils(getActivity()).setWeekType("近四周");
                                break;
                            case "近八周":
                                week_text.setText("近八周");
                                weekString = "eightWeek";
                                new SharedPreferencesUtils(getActivity()).setWeekType("近八周");
                                break;
                            case "本年累计":
                                week_text.setText("本年累计");
                                weekString = "year";
                                new SharedPreferencesUtils(getActivity()).setWeekType("本年累计");
                                break;
                            case "当前周":
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(getActivity()).setWeekType("当前周");
                                break;
                            default:
                                week_text.setText("当前周");
                                weekString = "current";
                                new SharedPreferencesUtils(getActivity()).setWeekType("当前周");
                                break;
                        }
                        break;
                    case 3:
                        measureStringTemp = dataMeasure.get(wheelview_single1.getCurrentPosition());
                        line_text.setText(measureString);
                        if (dataMeasure.get(wheelview_single1.getCurrentPosition()).equals("线上")) {
                            measureString = "online";
                            line_text.setText("线上");
                            new SharedPreferencesUtils(getActivity()).setLineType(1);
                        } else {
                            measureString = "offline";
                            line_text.setText("线下");
                            new SharedPreferencesUtils(getActivity()).setLineType(2);
                        }
                        break;
                }
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                getBrandScaleBasisRatio();
            }
        });
    }
    /**
     *获取上半部分规模同比
     * api/scale/brandScaleBasisRatio
     */
    private void getBrandScaleBasisRatio(){
        loading.setVisibility(View.VISIBLE);
        HashMap<String,Object> map = new HashMap<>();
        map.put("sellsType",saleString);
        map.put("linesType",measureString);
        map.put("timeType",weekString);
        StringBuffer sb = new StringBuffer();
        for(String str : userbrands){
            sb.append(str+",");
        }
        sb.deleteCharAt(sb.length()-1);
        map.put("competingBrands",sb.toString());
        map.put("category",scaleBasisRatioActivity.getCategory());
        map.put("brand","A.O.史密斯");
        map.put("lastWeek", new SharedPreferencesUtils(getActivity()).getNewWeek());
        ThreadPoolUtils.execute(new JsonRunnable(getActivity(),"HTTPGET", AvcConstants.URLHeaderBase+URL_ScaleBasisRatio,handler,map,1));

    }

    /***
     * 获取下半部分规模同比
     * api/scale/brandScaleRatioTrend
     */
    private void getScaleRatioTrend(){
        HashMap<String,Object> map = new HashMap<>();
        map.put("sellsType",saleString);
        map.put("linesType",measureString);
//        map.put("timeType","year");
        StringBuffer sb = new StringBuffer();
        for(String str : userbrands){
            sb.append(str+",");
        }
        sb.deleteCharAt(sb.length()-1);
        map.put("competingBrands",sb);
        map.put("category",scaleBasisRatioActivity.getCategory());
        map.put("brand","A.O.史密斯");
        map.put("lastWeek", new SharedPreferencesUtils(getActivity()).getNewWeek());
        ThreadPoolUtils.execute(new JsonRunnable(getActivity(),"HTTPGET", AvcConstants.URLHeaderBase+AvcConstants.URL_ScaleRatioTrend,handler,map,2));
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case -1:
                    loading.setVisibility(View.GONE);
                    break;
                case 1:
                    ScaleBasicRationInfo sbri = new Gson().fromJson(msg.obj.toString(),ScaleBasicRationInfo.class);
                    ArrayList<HashMap<String,String>> bardata = new ArrayList<>();
                    ArrayList<String> week = new ArrayList<>();
                    List<String> marketRatios = new ArrayList<>() ;
                    brands.clear();
                    for(int i=0;i<sbri.getReturnValue().size();i++){
                        HashMap<String,String> maps = new HashMap<>();
                        brands.add(sbri.getReturnValue().get(i).getBrand().trim());
                        if(saleString.equals("amount")){
                            maps.put("value",sbri.getReturnValue().get(i).getAmountBasisRatio()+"");
                            marketRatios.add(sbri.getReturnValue().get(i).getAmountBasisRatio());
                        }else{
                            maps.put("value",sbri.getReturnValue().get(i).getVolumeBasisRatio()+"");
                            marketRatios.add(sbri.getReturnValue().get(i).getVolumeBasisRatio());
                        }
                        if(sbri.getReturnValue().get(i).getBrand().equals("all")){
                            week.add("行业");
                            maps.put("key","行业");
                        }else{
                            week.add(sbri.getReturnValue().get(i).getBrand());
                            maps.put("key",sbri.getReturnValue().get(i).getBrand());
                        }
                        bardata.add(maps);
                    }
                    if(weekString.equals("current")){
                        week_text.setText(sbri.getMessage().toString().trim());
                    }
                    //设置表头的同环比数据
                    initMarketRatio(marketRatios);
                    getScaleRatioTrend();
                    initColumetChartView(mChart,bardata);
                    break;
                case 2:
                    loading.setVisibility(View.GONE);
                    ScaleRationTrendInfo srti = new Gson().fromJson(msg.obj.toString(),ScaleRationTrendInfo.class);
                    ArrayList<String> brandsData = new ArrayList<>();
                    //// TODO: 2017/9/18 这样会存在问题——当用户选择的竞品品牌没有返回数据时会闪退
                    ArrayList<ArrayList<HashMap<String, String>>> datas = new ArrayList<>();
                    brandsData.add("all");
                    brandsData.add("A.O.史密斯");
                    brandsData.addAll(userbrands);
                    for(int i=0;i<brandsData.size();i++){
                        ArrayList<HashMap<String, String>> data = new ArrayList<>();
                        for(int j=0;j<srti.getReturnValue().getWeeks().size();j++){
                            HashMap<String,String> maps = new HashMap<>();
                            for(ScaleRationTrendInfo.brandsDetails bd :srti.getReturnValue().getIndustryBrandOverviewBoTable().get(srti.getReturnValue().getWeeks().get(j))){
                                maps.put("key",srti.getReturnValue().getWeeks().get(j));
                                if(bd.getBrand().equals(brandsData.get(i))){
                                    if(saleString.equals("amount")){
                                        maps.put("value",bd.getAmountBasisRatio()+"");
                                    }else{
                                        maps.put("value",bd.getVolumeBasisRatio()+"");
                                    }
                                }
                            }
                            maps.put("value",(null == maps.get("value") || "".equals(maps.get("value"))?"0":maps.get("value")));
                            data.add(maps);
                        }
                        datas.add(data);
                    }
                    ArrayList<String> Allbrands = new ArrayList<>();
                    for(String str :brandsData){
                        if(str.equals("all")){
                            Allbrands.add("行业");
                        }else{
                            Allbrands.add(str.replace("[","").replace("]",""));
                        }
                    }
                    data = datas;
                    key = Allbrands;
                    setLineChartClick();
                    break;
                case -22:
                    loading.setVisibility(View.GONE);
                    Intent intent = new Intent ();
                    intent.setClass ( getActivity (), Login_Activity.class );
                    intent.setFlags ( Intent.FLAG_ACTIVITY_CLEAR_TASK );  //注意本行的FLAG设置
                    getActivity ().finish ();
                    startActivity ( intent );
                    break;
                default:
                    break;
            }
        }

        /***
         * 设置市占对标表头
         * @param brandsData 列表数据
         */
        private void initMarketRatio(List<String> brandsData) {
            for(TextView tv: marketRatio){
                tv.setVisibility(View.GONE);
            }
            for(int i=0;i<brandsData.size();i++){
                if(null == brandsData.get(i) ||"".equals(brandsData.get(i)) || "null".equals(brandsData.get(i))){
                    marketRatio.get(i).setTextColor(getActivity().getResources().getColor(R.color.text_one));
                    marketRatio.get(i).setText("--");
                    marketRatio.get(i).setVisibility(View.VISIBLE);
                }else{
                    marketRatio.get(i).setText(MyUtils.format2(Math.abs(Double.parseDouble(brandsData.get(i))))+"%");
                    marketRatio.get(i).setVisibility(View.VISIBLE);
                    if(Double.parseDouble(brandsData.get(i))<0){
                        marketRatio.get(i).setTextColor(getActivity().getResources().getColor(R.color.green));
                    }else{
                        marketRatio.get(i).setTextColor(getActivity().getResources().getColor(R.color.red));
                    }
                }

            }
        }

        /**
         * 设置可点击的lable标签
         */
        private void setLineChartClick(){
            listLable.clear ();
            for (int i = 0; i < key.size(); i++) {
                AllLableBean allbean = new AllLableBean();
                allbean.lable =key.get(i);
                if (colors2.get(i).equals(colors.get(i))){
                    allbean.selected = true;
                } else {
                    allbean.selected = false;
                }
                listLable.add ( allbean );
                Log.e("bean",""+allbean.selected);
            }
            adapter = new allLableAdapter ( listLable, colors, context );
            lableListView.setAdapter ( adapter );
            initNationalTrendData(data,key,colors2);
            lableListView.setOnItemClickListener ( new AdapterView.OnItemClickListener () {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    listLable.get ( position ).selected = !(listLable.get ( position ).selected);
                    if (listLable.get ( position ).selected) {
                        colors2.set(position,colors.get(position));
                    } else {
                        colors2.set(position,Color.parseColor ("#00000000"));
                    }
                    adapter.notifyDataSetChanged ();
                    initNationalTrendData(data,key,colors2);
                }
            } );



        }


        /***
         * 设置柱状图
         * @param chart
         * @param list
         */
        private void initColumetChartView(ColumnChartView chart,ArrayList<HashMap<String,String>> list) {
            chart.setZoomEnabled(false);//设置是否支持缩放
            chart.setOnValueTouchListener(new ColumnChartOnValueSelectListener() {
                @Override
                public void onValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
                    Log.e("选择的column:",""+value);
                }

                @Override
                public void onValueDeselected() {

                }
            });//为图表设置值得触摸事件
            chart.setInteractive(true);//设置图表是否可以与用户互动
            chart.setValueSelectionEnabled(true);//设置图表数据是否选中进行显示
            chart.setScaleY(0.9f);
            Axis axisX = new Axis();// X轴属性
            Axis axisY = new Axis().setHasLines(true);// Y轴属性
            ArrayList<AxisValue> axisValuesX = new ArrayList<AxisValue>();//定义X轴刻度值的数据集合
            List<Column> columns = new ArrayList<>();
            List<AxisValue> yValues = new ArrayList<>();
            for(int i=0;i<list.size();i++){
                ArrayList<SubcolumnValue> SubcolumnValues = new ArrayList<>();
                axisValuesX.add(new AxisValue(i).setLabel(list.get(i).get("key")));
                SubcolumnValue subcolumnValue = new SubcolumnValue();
                try {
                    subcolumnValue.setValue(Float.parseFloat(list.get(i).get("value")));
                    subcolumnValue.setLabel(list.get(i).get("value")+"%");
                }catch (Exception e){
                    subcolumnValue.setValue(0);
                    subcolumnValue.setLabel("0%");
                }
                subcolumnValue.setColor(getResources().getColor(R.color.ThemeColor));
                SubcolumnValues.add(subcolumnValue);
                Column column = new Column();
                column.setValues(SubcolumnValues);
                column.setHasLabels(true);
                column.setHasLabelsOnlyForSelected(false);
                columns.add(column);

                try {
                    AxisValue uValue = new AxisValue(Float.parseFloat(list.get(i).get("value")));
                    yValues.add(uValue);
                }catch (Exception e){
                    AxisValue uValue = new AxisValue(0);
                    yValues.add(uValue);
                }



            }
            axisX.setName("");//设置X轴显示名称
            axisX.setValues(axisValuesX);//为X轴显示的刻度值设置数据集合
            axisX.setLineColor(getResources().getColor(R.color.background_gray));// 设置X轴轴线颜色
            axisX.setTextColor(getResources().getColor(R.color.text_color));// 设置X轴文字颜色
            axisX.setTextSize(8);// 设置X轴文字大小
            axisX.setTypeface(Typeface.DEFAULT);// 设置文字样式，此处为默认
            axisX.setHasTiltedLabels(false);// 设置X轴文字向左旋转45度
            axisX.setHasLines(false);// 是否显示X轴网格线
            axisX.setHasSeparationLine(false);// 设置是否有分割线
            axisX.setInside(false);// 设置X轴文字是否在X轴内部

            axisY.setTextSize(8);// 设置X轴文字大小
            axisY.setTextColor(getResources().getColor(R.color.text_one));
            axisY.setLineColor(getResources().getColor(R.color.text_one));// 设置Y轴轴线颜色
            axisY.setTypeface(Typeface.DEFAULT);// 设置文字样式，此处为默认
            axisY.setValues(yValues);
            axisY.setAutoGenerated(true);

            ColumnChartData columnChartData = new ColumnChartData();
            columnChartData.setColumns(columns);
            columnChartData.setAxisYLeft(axisY);// 将Y轴属性设置到左边
            columnChartData.setAxisXBottom(axisX);// 将X轴属性设置到底部
            columnChartData.setValueLabelBackgroundAuto(false);// 设置数据背景是否跟随节点颜色
            columnChartData.setValueLabelBackgroundColor(Color.BLUE);// 设置数据背景颜色
            columnChartData.setValueLabelBackgroundEnabled(false);// 设置是否有数据背景
            columnChartData.setValueLabelsTextColor(getResources().getColor(R.color.text_one));// 设置数据文字颜色
            columnChartData.setValueLabelTextSize(8);// 设置数据文字大小
            columnChartData.setValueLabelTextSize(0);
            chart.setColumnChartData(columnChartData);
        }
    };

    /***
     * 设置折线图
     * @param data
     * @param key
     */
    @SuppressWarnings("deprecation")
    private void initNationalTrendData(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> key,ArrayList<Integer> colors) {
        //设置手势滑动事件
        linechart_view.setOnChartGestureListener(this);
        //设置数值选择监听
        linechart_view.setOnChartValueSelectedListener(this);
        //后台绘制
        linechart_view.setDrawGridBackground(false);

        //设置描述文本
        linechart_view.getDescription().setEnabled(false);
        // enable touch gestures
        linechart_view.setTouchEnabled(true); // 设置是否可以触摸
        linechart_view.setDragEnabled(true);// 是否可以拖拽
//        linechart_view.setClickable(false);
//        linechart_view.setClipValuesToContent(false);
//        linechart_view.setContextClickable(false);
        linechart_view.setScaleEnabled(false);// 是否可以缩放 x和y轴, 默认是true
        linechart_view.setPinchZoom(false);  //设置x轴和y轴能否同时缩放。默认是否
        linechart_view.setDoubleTapToZoomEnabled(false);//设置是否可以通过双击屏幕放大图表。默认是true
        linechart_view.setHighlightPerDragEnabled(false);//能否拖拽高亮线(数据点与坐标的提示线)，默认是true
        linechart_view.setDragDecelerationEnabled(false);//拖拽滚动时，手放开是否会持续滚动，默认是true（false是拖到哪是哪，true拖拽之后还会有缓冲）
        linechart_view.setDragDecelerationFrictionCoef(0.99f);//与上面那个属性配合，持续滚动时的速度快慢，[0,1) 0代表立即停止。
        linechart_view.setFocusableInTouchMode(false);
//        linechart_view.setTouchscreenBlocksFocus(false);
        // 是否在折线图上添加边框
        linechart_view.setDrawBorders(false);
        linechart_view.setNoDataText("没有相关数据");

        if (data.size() != 0) {
            linechart_view.moveViewToX(getWeekXCoord(data).size());
        }

        //设置X轴
        XAxis xAxis = linechart_view.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextSize(8f);
        xAxis.setTextColor(getResources().getColor(R.color.text_color));
        xAxis.setDrawAxisLine(true);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        xAxis.setAvoidFirstLastClipping(true);

        if (data.size() != 0) {
            xAxis.setValueFormatter(new MyXValueFormatter(getWeekXCoord(data)));
        }

        YAxis leftAxis = linechart_view.getAxis(YAxis.AxisDependency.LEFT);//确定表示图表的侧面
        linechart_view.getAxisRight().setEnabled(false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setTextSize(6f);
        leftAxis.setTextColor(getResources().getColor(R.color.text_color));
//        leftAxis.setDrawZeroLine(true);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setDrawGridLines(true);
//        leftAxis.resetAxisMinValue();
        leftAxis.enableGridDashedLine(2f, 10f, 1f);
        if (data.size() != 0) {
            //y轴最小
            leftAxis.setAxisMinValue(getMinYValue(data, key));
            //y轴最大
            leftAxis.setAxisMaxValue(getMaxYValue(data, key));
        }

        // 限制数据(而不是背后的线条勾勒出了上面)
        leftAxis.setDrawLimitLinesBehindData(true);

        leftAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (int)value+"%";
            }
        });

        // 设置比例图标示，就是那个一组y的value的
        Legend mLegend = linechart_view.getLegend();
        mLegend.setPosition(Legend.LegendPosition.ABOVE_CHART_CENTER);
        mLegend.setForm(Legend.LegendForm.LINE);// 样式
        mLegend.setFormSize(15.0f);// 字体
        mLegend.setWordWrapEnabled(true);
        mLegend.setTextColor(Color.DKGRAY);// 颜色
        mLegend.setEnabled ( false );

//        Matrix matrix = new Matrix();
//        int tempSize = getWeekXCoord(data).size();
//        matrix.postScale(tempSize / 8, 1f);
//        // 在图表动画显示之前进行缩放
//        linechart_view.getViewPortHandler().refresh(matrix, linechart_view, false);

        if (data.size() != 0) {
            //设置数据
            trendDataAmend(data, key,colors);
            linechart_view.setVisibleXRangeMaximum(8);
        }

        //默认动画
        linechart_view.animateX(1000);
//        linechart_view.animateXY(1000,1000);

        linechart_view.invalidate();

    }

    //获取星期数
    private ArrayList<String> getWeekXCoord(ArrayList<ArrayList<HashMap<String, String>>> data) {
        ArrayList<String> temp = new ArrayList<>();
//        Log.e("data","--------获取星期数---------"+data.size());
        for (int a = 0, b = data.get(0).size(); a < b; a++) {
            HashMap<String, String> hashMap = data.get(0).get(a);
            String key = hashMap.get("key").toString().trim();
            String value = hashMap.get("value").toString().trim();
            temp.add(key);

        }
        return temp;
    }


    //获取最大值
    private float getMaxYValue(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> keyBrand) {
        float endValue = 20f;
        for (int i = 0; i < keyBrand.size(); i++) {
            for (int a = 0, b = data.get(i).size(); a < b; a++) {
                HashMap<String, String> hashMap = data.get(i).get(a);
                String key = hashMap.get("key").toString().trim();
                String value = hashMap.get("value").toString().trim();
                if (!TextUitl.isEmpty(value)) {
                    float tempValue = Float.valueOf(value);
                    endValue = tempValue > endValue ? tempValue : endValue;
                }
            }

        }
        return Math.round(endValue + 10f);
    }


    //获取最小值
    private float getMinYValue(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> keyBrand) {
        float endValue = -2f;
        for (int i = 0; i < keyBrand.size(); i++) {
            for (int a = 0, b = data.get(i).size(); a < b; a++) {
                HashMap<String, String> hashMap = data.get(i).get(a);
                String key = hashMap.get("key").toString().trim();
                String value = hashMap.get("value").toString().trim();
                if (!TextUitl.isEmpty(value)) {
                    float tempValue = Float.valueOf(value);
                    endValue = tempValue < endValue ? tempValue : endValue;
                }
            }

        }
        return Math.round(endValue - 2f);
    }


    //线性图数据
    @SuppressWarnings("deprecation")
    private void trendDataAmend(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> keyBrand,ArrayList<Integer> colors) {
        ArrayList<String> xString = new ArrayList<>();//X坐标的值
        ArrayList<ILineDataSet> mLineDataSets = new ArrayList<>();

        for (int i = 0; i < keyBrand.size(); i++) {
            ArrayList<Entry> yString = new ArrayList<>();//Y坐标的值
            for (int a = 0, b = data.get(i).size(); a < b; a++) {
                HashMap<String, String> hashMap = data.get(i).get(a);
                String key = hashMap.get("key").toString().trim();
                String value = hashMap.get("value").toString().trim();
                xString.add(key);
                if (TextUitl.isEmpty(value)) {
                    if (data.get(i).size() < 8) {
                        yString.add(new Entry(a + 1, 0));
                    } else {
                        yString.add(new Entry(a, 0));
                    }
                } else {
                    if (data.get(i).size() < 8) {
                        yString.add(new Entry(a + 1, TextUitl.retainTwoDecimalsFloat(value)));
                    } else {
                        yString.add(new Entry(a, TextUitl.retainTwoDecimalsFloat(value)));
                    }
                }
            }
            // y轴数据集
            LineDataSet mLineDataSet = new LineDataSet(yString, keyBrand.get(i));

            mLineDataSet.setDrawValues(false);
            // 线宽
            mLineDataSet.setLineWidth(1.0f);
            // 显示的圆形大小
            mLineDataSet.setCircleSize(2.0f);
            mLineDataSet.setDrawCircleHole(true);
            // 折线的颜色
            mLineDataSet.setColor(colors.get(i));
            // 圆球的颜色
            mLineDataSet.setCircleColor(colors.get(i));
            // 填充曲线下方的区域，红色，半透明。
            mLineDataSet.setDrawFilled(false);
            mLineDataSet.setFillAlpha(40);
            mLineDataSet.setFillColor(colors.get(i));
            mLineDataSets.add(mLineDataSet);

        }
        LineData mLineData = new LineData(mLineDataSets);
        linechart_view.getXAxis().setAxisMaximum(mLineData.getXMax() + 1);
        linechart_view.setData(mLineData);

    }

    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
// 完成之后停止晃动
        if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
            linechart_view.highlightValues(null);
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

}
